<template>
  <div v-loading="state.loading" class="container">
    <template v-if="props.isEdit">
      <MerakEditTable v-bind="editState" style="height: 230px">
        <template #factory_id="{ scope }">
          <el-select
            v-model="(scope as Record<string, any>).factory_id.value"
            filterable
            remote
            remote-show-suffix
            :placeholder="$t('goods_document.search_company_name')"
            :remote-method="(query: string) => handleRemote(query, scope.index)"
            @change="
              value =>
                ((scope as Record<string, any>).factory_id.label = state.options.find(option => option.value === value)?.label)
            "
          >
            <el-option v-for="option in renderOptions(scope.index)" :value="option.value" :label="option.label" />
          </el-select>
        </template>
        <template #handle="{ row }">
          <el-button type="danger" link @click="handleDeleteRow(row)">{{ $t("merak.delete") }}</el-button>
        </template>
      </MerakEditTable>
    </template>
    <template v-else>
      <div class="handle">
        <el-input
          v-model="searchValue" 
          :placeholder="$t('goods_document.factory')"
          :suffix-icon="Search"
          clearable
        @change="init(state.certifyObj)"
      />
      <el-button link @click="init(state.certifyObj,'init')">{{ $t("merak.refresh") }}</el-button>
      </div>
      <el-table class="merak-table-container" table-layout="auto" :data="state.data" :max-height="300" scrollbar-always-on>
        <el-table-column prop="factory_id" :label="$t('goods_document.factory_id')" width="150px"/>
        <el-table-column prop="factory_name_certify" :label="$t('goods_document.factory_name_certify')" />
        <el-table-column prop="factory_address_certify" :label="$t('goods_document.factory_address_certify')" />
        <template #empty>
          <div v-if="state.loadedData" style="padding: 100px 40px 0">
            <img :src="EmptyPng" style="object-fit: cover; height: 130px" />
          </div>
          <div v-else></div>
        </template>
      </el-table>
    </template>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from "vue";

import { useRoute } from "vue-router";

import { ElMessage, ElSelect, ElOption, ElInput, ElButton, ElTable, ElTableColumn } from "element-plus";
import { Search } from "@element-plus/icons-vue";

import MerakEditTable from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { OptionType, getTableData, getCompanyOptions, saveCompany } from "@/api/modules/goodsArchive/document";

import { confirmWarningMsg } from "@/utils/messageUtils";

import EmptyPng from "@/assets/images/empty.png";
import { getCertifyApi, getProductInfoApi } from "@/api/modules/goodsArchive/list/detail";
type EditTableDataType = Record<
  string,
  {
    value?: string | number;
    label?: string;
    errTip?: string;
  }
>;

const props = defineProps<{
  queueId?: string;
  isEdit: boolean;
   productId?: string|number;
}>();

const currentInstance = getCurrentInstance();

const route = useRoute();

const searchValue = ref<string>();

const recordNum = ref(0);

const state = reactive<{
  certifyObj:object,
  loading: boolean;
  loadedData: boolean;
  options: OptionType[];
  searchOptions: OptionType[];
  data: Array<Record<string, any>>;
}>({
  certifyObj:{},
  loading: false,
  loadedData: false,
  options: [],
  searchOptions: [],
  data: []
});

// 编辑表格数据
const editState = reactive<{
  headData: Array<Record<string, any>>;
  tableData: EditTableDataType[];
  headConfig: Record<string, any>;
}>({
  headData: [{ field: "factory_id", title: currentInstance?.proxy?.$t("goods_document.factory_name_certify") }],
  tableData: [],
  headConfig: {
    factory_id: { isEdit: true }
  }
});

// 过滤下拉选项
const handleRemote = (query: string, index: number) => {
  const options = !!query ? state.options.filter(option => option.label.toLowerCase().includes(query.toLowerCase())) : [];
  const excludeIds = editState.tableData.map((item, idx) => (index === idx ? undefined : item.factory_id?.value)).filter(Boolean);
  state.searchOptions = options.filter(option => !excludeIds.includes(option.value));
};

// 查找当前下拉选项
const renderOptions = (index: number) => {
  const currentValue = editState.tableData?.[index]?.factory_id?.value;
  const queryOptions = state.options.filter(option => option.value === currentValue);
  return state.searchOptions.some(option => option.value === currentValue)
    ? state.searchOptions
    : [...state.searchOptions, ...queryOptions];
};

const handleDeleteRow = (row: any) => {
  if (typeof row?.index === "number") {
    editState.tableData.splice(row.index, 1);
  }
};

const init = async (certifyObj,type) => {
  state.certifyObj=certifyObj;
    state.loading = !!props.queueId ? false : true;
  await getProductInfoApi({ product_id: props.productId, goods_certify_id: certifyObj?.goods_certify_id, type: "cnCompany" },props.queueId).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      if(type=="init"){
        searchValue.value="";
      }
      const filterValue = (searchValue.value ?? "").toLowerCase();
      recordNum.value = data.length;
      state.loadedData = true;
      state.data = data.filter(item => (item.factory_name_certify ?? "").toLowerCase().includes(filterValue));
    }
  });
  state.loading = false;
};

onMounted(() => {
  // init({},"init");
  getCompanyOptions().then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      state.options = data;
    }
  });
});

defineExpose({
  init,
  reload: () => init({},"init"), 
  recordNum
});
</script>

<style scoped lang="scss">
.handle {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--merak-space);
  .el-input {
    width: 200px;
  }
  .el-button {
    margin: 0;
    padding: 0;
    min-width: auto;
    border: none;
    &:hover,
    &:focus {
      color: var(--el-color-primary) !important;
    }
  }
}
</style>
